<template>
  <div class="app-container">
    <div
      v-show="
        !applicationDetailsInfo.visible &&
        !detailInfo.visible &&
        !modifyInfo.visible &&
        !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slipSelectRequest="slipSelectRequest"
          :clearType="clearType"
        >
          <template v-slot:filter-useApplicationId>
            <el-input
              v-model="useApplicationName"
              class="not-mongolia"
              type="input"
              placeholder="请选择领用人"
              :disabled="true"
            >
              <template #append>
                <el-icon @click="showSelectUser"><MoreFilled /></el-icon>
              </template>
            </el-input>
          </template>
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-storage>
            <el-button :disabled="!canStorage" @click="storageSelect"
              >入库</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
        @sortChange="sortChange"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-applicationOrderNo="scope">
          <span
            class="slip-edit"
            v-if="$permission('useStoreApplication:details')"
            @click="showApplicationDetail(scope.row)"
            >{{ scope.row.applicationOrderNo }}</span
          >
          <span v-else>{{ scope.row.applicationOrderNoo }}</span>
        </template>
        <template v-slot:col-updateUserName="scope">
          <span>{{
            scope.row.status === 'complete'
              ? scope.row.updateUserName || '-'
              : '-'
          }}</span>
        </template>
        <template v-slot:col-updateTime="scope">
          <span>{{
            scope.row.status === 'complete' ? scope.row.storageTime || '-' : '-'
          }}</span>
        </template>
      </TableContainer>
    </div>
    <!-- 明细 -->
    <export-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      :id="detailInfo.id"
      :order-no="detailInfo.orderNo"
      @returnBack="getList"
    />
    <use-application-details
      v-if="applicationDetailsInfo.visible"
      v-model:visible="applicationDetailsInfo.visible"
      :title="applicationDetailsInfo.title"
      :id="applicationDetailsInfo.id"
      @returnBack="getList"
    />
    <select-use-application-user
      v-if="applicationUserInfo.visible"
      v-model:show-dialog="applicationUserInfo.visible"
      :api="applicationUserInfo.api"
      :highlight-row="true"
      :check-box="false"
      @callback="selectUser"
    ></select-use-application-user>
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <use-application-modify
      v-if="modifyInfo.visible"
      :orderId="''"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      fromType="useStore"
      saveFrom="useStore"
      :storeOrderId="modifyInfo.id"
      :storeOrderNo="modifyInfo.orderNo"
      :useReturnImportStore="''"
      @returnModify="returnModify"
    />
  </div>
</template>

<script setup name="useStorage">
import {
  inBound,
  inHospitalBound,
  getUseExportCustomizeList,
  validateRevoke,
} from '@/api/use.js'
import ExportDetail from './details'
import { getRrgUserList } from '@/api/base'
import UseApplicationDetails from './../application/details'
import UseApplicationModify from '@/views/useReturn/application/modify'
import SelectUseApplicationUser from '@/components/SelectUseApplicationUser/index'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance()
const detailList = defineAsyncComponent(() => import('./detailList'))
const selectRows = ref([])
const useApplicationName = ref('')
const slipSelectRequest = ref(true)
const clearType = ref(true)
const time = ref([])
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      depotIdAuth: {
        asTbName: 'use_export_order',
        columnName: 'store_depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
    customizeUserVO: {},
    queryParams: {
      status: [1, 3],
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'storage',
      show: proxy.$permission('useStoreApplication:store'),
    },
    {
      type: 'slot',
      value: 'retract',
      show: proxy.$permission('useExportApplication:retract'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  selections: [],
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '入库',
        event: storage,
        show: proxy.$permission('useStoreApplication:store'),
        ifRender(row) {
          return row.status === 1
        },
      },
      {
        label: '入库(分院)',
        event: storageHospital,
        show: true,
        ifRender: function (row) {
          return row.showStorageHospital === true
        },
      },
      {
        label: '领用退回',
        event: revoke,
        show: proxy.$permission('useStoreApplication:revoke'),
        ifRender: function (row) {
          return row.status === 3 && row.storeDepotIsCargoSpaceManage != 1
        },
      },
    ],
  },
})
const detailInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const applicationDetailsInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const applicationUserInfo = ref({
  visible: false,
  api: getRrgUserList,
})
const modifyInfo = ref({
  visible: false,
  title: '领用退回',
  id: '',
  orderNo: '',
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const canStorage = computed(() => {
  return (
    selectRows.value.filter((item) => item.status !== 1).length === 0 &&
    selectRows.value.length > 0
  )
})
watch(
  () => applicationDetailsInfo.value,
  (val) => {
    if (!val) {
      getList()
    }
  }
)
watch(
  () => filterInfo.value.query.storageTimeGreater,
  (val) => {
    if (!val) {
      time.value = null
    }
  }
)
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function revoke(row) {
  validateRevoke(row.id).then((resp) => {
    if (resp && resp.success) {
      modifyInfo.value.visible = true
      modifyInfo.value.id = row.id
      modifyInfo.value.orderNo = row.orderNo
    }
  })
}
function returnModify() {}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'use_export_order',
      columnName: 'store_depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.orderNo = row.orderNo
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function showApplicationDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  applicationDetailsInfo.value.id = row.applicationOrderId
  applicationDetailsInfo.value.visible = true
}
function showSelectUser() {
  applicationUserInfo.value.visible = true
}
function selectUser(row) {
  filterInfo.value.query.useApplicationUserIdMult = row.id
  useApplicationName.value = row.name
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      selectRows.value = data
      break
  }
}
//行入库
function storage(row) {
  ElMessageBox.confirm('此操作将更新数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      let param = []
      param.push(row.id)

      inBound(param).then((res) => {
        if (res.success) {
          getList()
        }
      })
    })
    .catch((e) => {})
}
function storageHospital(row) {
  let ids = [row.id]
  inHospitalBound(ids).then((res) => {
    if (res.success) {
      getList()
    }
  })
}
//批量入库
function storageSelect() {
  if (selectRows.value.length != 0) {
    let ids = []
    let firstStatus = 1
    let isOnly = true
    selectRows.value.forEach((row) => {
      if (firstStatus != row.status) {
        isOnly = false
        return
      }
      ids.push(row.id)
    })
    if (!isOnly) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '只能选择状态为待入库的数据',
      })
      return
    }
    inBound(ids).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请选择一条操作数据',
    })
  }
}

function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'useExportOrderInIndex-com.slip.spd.entity.vo.use.UseExportOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getUseExportCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    onlyShowOption: ['1', '3'],
    code: 'use_storage_status',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
